package com.pm.controller.dept;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pm.common.Pages;
import com.pm.common.Response;
import com.pm.common.annotation.MyLog;
import com.pm.common.annotation.UserLoginToken;
import com.pm.common.exception.ExpCodeState;
import com.pm.entity.po.dept.Department;
import com.pm.entity.po.dept.DepartmentType;
import com.pm.entity.po.dept.DeptNamePo;
import com.pm.entity.po.task.Task;
import com.pm.entity.vo.dept.DeptTaskVO;
import com.pm.entity.vo.dept.DeptVO;
import com.pm.service.dept.DepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Api(tags = "部门管理")
@UserLoginToken
@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;

    @ApiOperation("新增接口")
    @PostMapping("/add")
    @ResponseBody
    @MyLog(value = "新增部门信息")
    public Response<Integer> add(Department department) {
        Response<Integer> response = null;
        Integer result = departmentService.add(department);
        if (result > 0) {
            response = new Response<>(ExpCodeState.add_data_success, result);
        } else {
            response = new Response<>(ExpCodeState.add_data_failed);
        }
        return response;
    }

    @ApiOperation("更新接口")
    @PostMapping("/update")
    @ResponseBody
    @MyLog(value = "编辑部门信息")
    public Response<Integer> update(Department department) {
        Response<Integer> response = null;
        Integer result = departmentService.update(department);
        if (result > 0) {
            response = new Response<>(ExpCodeState.update_data_success, result);
        } else {
            response = new Response<>(ExpCodeState.update_data_failed);
        }
        return response;
    }

    @ApiOperation("删除接口")
    @PostMapping("/remove")
    @ResponseBody
    @MyLog(value = "删除部门信息")
    public Response<Integer> remove(Department department) {
        Response<Integer> response = null;
        Integer result = departmentService.remove(department);
        if (result > 0) {
            response = new Response<>(ExpCodeState.remove_data_success, result);
        } else {
            response = new Response<>(ExpCodeState.remove_data_failed);
        }
        return response;
    }

    @ApiOperation("单个对象查询接口")
    @PostMapping("/load")
    @ResponseBody
    public Response<Department> load(Department department) {
        Response<Department> response = null;
        Department result = departmentService.load(department);
        response = new Response<Department>(ExpCodeState.query_data_success, result);
        return response;
    }

    @ApiOperation("全部列表查询接口")
    @PostMapping("/getList")
    @ResponseBody
    public Response<List<Department>> getList(Department department) {
        List<Department> result = departmentService.getList(department);
        Response<List<Department>> res = new Response<List<Department>>(ExpCodeState.query_data_success, result);
        return res;
    }

    @ApiOperation("上半年排名统计列表查询接口")
    @PostMapping("/getDeptVOList/{pageNum}/{pageSize}")
    @ResponseBody
    public Response<PageInfo<DeptVO>> getDeptVOList(@RequestBody DeptVO vo, Pages page) {
        PageHelper.startPage(page);
        PageInfo<DeptVO> pageT = new PageInfo<>(departmentService.getDeptVOList(vo.getId()));
        PageHelper.clearPage();
        Response<PageInfo<DeptVO>> res = new Response<PageInfo<DeptVO>>(ExpCodeState.query_data_success, pageT);
        return res;
    }

    @ApiOperation("排名统计列表查询接口")
    @PostMapping(value = "/getDeptVOList1/{pageNum}/{pageSize}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String getDeptVOList1(@RequestBody DeptVO vo, Pages page) {
        PageHelper.startPage(page);
        PageInfo<DeptVO> pageT = new PageInfo<>(departmentService.getDeptVOList(vo.getId()));
        List<DeptVO> result = pageT.getList();
        System.out.println(JSON.toJSONString(result));
        PageHelper.clearPage();
        Task task = new Task();
        task.setYear("2020");
        List<Task> tasks = departmentService.getTaskList(task);
        System.out.println(JSON.toJSONString(tasks));
        Map<Integer, Integer> ids = new HashMap<>();
        StringBuffer str = new StringBuffer();
        str.append("<table border='1' cellspacing='0' cellpadding='10' width='100%' style='border:1px solid #EBEEF5;'>");
        str.append(" <thead style='color:#909399; background:#f5f5f5;font-size:10px;'>");
        str.append("<tr class='firstHead'>");
        str.append("<th colspan='1' rowspan='4' style='padding: 10px;'>区县/重点工作</th>");
        for (Task t : tasks) {
            if (t.getChildren().isEmpty()) {
                str.append("<th colspan='12' rowspan='2' style='padding: 10px;'>" + t.getName() + "</th>");
            } else {
                str.append("<th colspan='" + t.getChildren().size() * 12 + "' rowspan='1' style='padding: 10px;'>" + t.getName() + "</th>");
            }
        }
        str.append("</tr>");
        str.append("<tr class='firstHead'>");
        for (Task t : tasks) {
            if (!t.getChildren().isEmpty()) {
                for (Task t1 : t.getChildren())
                    str.append("<th colspan='12' rowspan='1' style='padding: 10px;'>" + t1.getName() + "</th>");
            }
        }
        str.append("</tr>");
        str.append("<tr class='firstHead'>");
        int i = 0;
        for (Task t : tasks) {
            if (t.getChildren().isEmpty()) {
                ids.put(i, t.getId());
                i += 1;
                str.append("<th colspan='3' rowspan='1' style='padding: 10px;'>一季度</th>");
                str.append("<th colspan='3' rowspan='1' style='padding: 10px;'>二季度</th>");
                str.append("<th colspan='3' rowspan='1' style='padding: 10px;'>三季度</th>");
                str.append("<th colspan='3' rowspan='1' style='padding: 10px;'>四季度</th>");
            } else {
                for (Task t1 : t.getChildren()) {
                    ids.put(i, t1.getId());
                    i += 1;
                    str.append("<th colspan='3' rowspan='1' style='padding: 10px;'>一季度</th>");
                    str.append("<th colspan='3' rowspan='1' style='padding: 10px;'>二季度</th>");
                    str.append("<th colspan='3' rowspan='1' style='padding: 10px;'>三季度</th>");
                    str.append("<th colspan='3' rowspan='1' style='padding: 10px;'>四季度</th>");
                }
            }
        }
        str.append("</tr>");
        str.append("<tr class='firstHead'>");
        for (Task t : tasks) {
            if (t.getChildren().isEmpty()) {
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>得分</th>");
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>排名</th>");
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>亮灯</th>");
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>得分</th>");
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>排名</th>");
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>亮灯</th>");
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>得分</th>");
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>排名</th>");
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>亮灯</th>");
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>得分</th>");
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>排名</th>");
                str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>亮灯</th>");
            } else {
                for (int i1 = 0; i1 < t.getChildren().size(); i1++) {
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>得分</th>");
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>排名</th>");
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>亮灯</th>");
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>得分</th>");
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>排名</th>");
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>亮灯</th>");
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>得分</th>");
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>排名</th>");
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>亮灯</th>");
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>得分</th>");
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>排名</th>");
                    str.append("<th colspan='1' rowspan='1' style='padding: 10px;'>亮灯</th>");
                }
            }
        }
        str.append("</tr>");
        str.append(" </thead>");
        str.append(" <tbody>");
        for (DeptVO v : result) {
            str.append("<tr class=''>");
            str.append("<td colspan='1' rowspan='1'>" + v.getName() + "</td>");
            for (int j = 0; j < v.getDeptTasks().size(); j++) {
                Integer id = ids.get(j);
                Optional<DeptTaskVO> cartOptional = v.getDeptTasks().stream().filter(item -> item.getTaskId() == id)
                        .findFirst();

                if (cartOptional.isPresent()) {
                    DeptTaskVO dt1 = cartOptional.get();
                    String url = "";
                    if (dt1.getCaveat() != null && dt1.getCaveat() > 0) {
                        String name = dt1.getCaveat() == 1 ? "yellowLight" : "redLight";
                        url = "<img src=''../../assets/img/" + name + ".png' alt=''>";
                    }
                    str.append("<td colspan='1' rowspan='1'>" + dt1.getOneQuarterScore() + "</td>");
                    str.append("<td colspan='1' rowspan='1'>" + dt1.getOneQuarterRank() + "</td>");
                    str.append("<td colspan='1' rowspan='1'>" + url + "</td>");
                    str.append("<td colspan='1' rowspan='1'>" + dt1.getTwoQuarterScore() + "</td>");
                    str.append("<td colspan='1' rowspan='1'>" + dt1.getTwoQuarterRank() + "</td>");
                    str.append("<td colspan='1' rowspan='1'>" + url + "</td>");
                    str.append("<td colspan='1' rowspan='1'>" + dt1.getThreeQuarterScore() + "</td>");
                    str.append("<td colspan='1' rowspan='1'>" + dt1.getThreeQuarterRank() + "</td>");
                    str.append("<td colspan='1' rowspan='1'>" + url + "</td>");
                    str.append("<td colspan='1' rowspan='1'>" + dt1.getFourQuarterScore() + "</td>");
                    str.append("<td colspan='1' rowspan='1'>" + dt1.getFourQuarterRank() + "</td>");
                    str.append("<td colspan='1' rowspan='1'>" + url + "</td>");
                }
            }
            str.append("</tr>");
        }
        str.append(" </tbody>");
        str.append(" </table>");
        return str.toString().replace("null", "-");
    }

    @ApiOperation("分页查询接口")
    @PostMapping("/getListByPage/{pageNum}/{pageSize}")
    @ResponseBody
    @MyLog(value = "查询部门信息")
    public Response<PageInfo<Department>> getList(Department department, Pages page) {
        PageInfo<Department> result = departmentService.getListByPage(department, page);
        Response<PageInfo<Department>> res = new Response<PageInfo<Department>>(ExpCodeState.query_data_success, result);
        return res;
    }

    @ApiOperation("查询分类列表接口")
    @PostMapping("/getDepartmentTypeList")
    @ResponseBody
    public Response<List<DepartmentType>> getDepartmentTypeList() {
        List<DepartmentType> result = departmentService.getListByType();
        Response<List<DepartmentType>> res = new Response<>(ExpCodeState.query_data_success, result);
        return res;
    }

    @ApiOperation("查询有任务的部门列表接口(不包含零时工作组)")
    @PostMapping("/getDepartmentTypeNotFiveList")
    @ResponseBody
    public Response<List<DepartmentType>> getDepartmentTypeNotFiveList() {
        List<DepartmentType> result = departmentService.getListByTypeNotFive();
        Response<List<DepartmentType>> res = new Response<>(ExpCodeState.query_data_success, result);
        return res;
    }

    @ApiOperation("查询有打分的部门列表接口(不包含零时工作组)")
    @PostMapping("/getHaveScoreDeptList")
    @ResponseBody
    public Response<List<DepartmentType>> getHaveScoreDeptList() {
        List<DepartmentType> result = departmentService.getHaveScoreDeptList();
        Response<List<DepartmentType>> res = new Response<>(ExpCodeState.query_data_success, result);
        return res;
    }

    /**
     * 根据id查部门
     * @return
     */
    @ApiOperation("根据类别Id查询部门")
    @PostMapping("/getAllDepartmentTypeId")
    @ResponseBody
    public Response<List<Department>> getAllDepartment(Integer id) {
        List<Department> Departments = departmentService.Departments(id);
        Response<List<Department>> response = new Response<>(ExpCodeState.query_data_success, Departments);
        return response;
    }

    /**
     * 根据目标任务Id查相关部门及类别
     */
    @ApiOperation("根据重点任务Id查相关部门及类别")
    @PostMapping("/getAllDepartmentT")
    @ResponseBody
    public Response<List<DepartmentType>> getAllDepartmentT(Integer id) {
        List<DepartmentType> departmentAndTypes = departmentService.getAllDepartmentT(id);
        Response<List<DepartmentType>> response = new Response<>(ExpCodeState.query_data_success, departmentAndTypes);
        return response;
    }

    @ApiOperation("表头")
    @PostMapping("/getAlltask")
    @ResponseBody
    public Response<List<Task>> getAlltask() {
        Task task = new Task();
        task.setYear("2020");
        List<Task> tasks = departmentService.getTaskList(task);
        Response<List<Task>> response = new Response<>(ExpCodeState.query_data_success, tasks);
        return response;
    }

    @ApiOperation("查询所有部门id和名称")
    @PostMapping("/getAllDeptName")
    @ResponseBody
    public Response<List<DeptNamePo>> getAllDeptName() {
        List<DeptNamePo> result = departmentService.getAllDeptName();
        Response<List<DeptNamePo>> res = new Response<>(ExpCodeState.query_data_success, result);
        return res;
    }
}
